const Router = require("koa-router");
const { redis } = require("@core/redis");
const { Op } = require("sequelize");
const { News } = require("@models/news");
const { Admin } = require("@models/admin");
const { Auth } = require("@middlewares/auth");
const { Favor } = require("@models/favor");
const axios = require("axios");
const schedule = require("node-schedule");

// 获取access_token  1111
AccessToken = async () => {
  let access_token = await redis.get("article");
  if (!access_token) {
    let appid = "wx97fe97e84bb5b905";
    let secret = "567282f62042f3442129075664521e36";
    let res = await axios.get(
      `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`
    );
    access_token = res.data.access_token;

    await redis.set(
      "article",
      access_token,
      "EX",
      60 * 60 // 缓存1小时
    );
  }

  return access_token;
};

// 获取文章列表
getArticles = async () => {
  // 获取access_token
  const access_token = await AccessToken();
  // 获取文章列表

  try {
    let res = await axios.post(
      `https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token=${access_token}`,
      {
        offset: 0,
        count: 20,
        no_content: 0,
      }
    );
    return res.data;
  } catch (e) {
    console.log(e);
  }

};

// 异步获取文章
asyncArticles = async () => {
  const data = await getArticles();
  for (let i = 0; i < data.item.length; i++) {
    for (let j = 0; j < data.item[i].content.news_item.length; j++) {
      let item = await redis.get(
        `article:${data.item[i].content.news_item[j].url}`
      );

      if (!item) {
        let data_item = data.item[i].content.news_item[j];
        await redis.set(
          `article:${data_item.url}`,
          JSON.stringify(data_item.title)
        );
        try {
          await News.create({
            title: data_item.title,
            url: data_item.url,
            content: data_item.content,
            image: data_item.thumb_url,
            digest: data_item.digest,
            author: data_item.author,
            admin_id: 4,
            is_del: 1,
          });
        } catch (e) {
          console.log(data_item.title, "创建失败");
        }
      }
    }
  }
};

const async_articles = schedule.scheduleJob("0 1 * * * ", asyncArticles);

process.on("SIGINT", function () {
  // 取消定时任务
  async_articles.cancel();
  // 退出进程
  process.exit();
});
process.on("SIGTERM", function () {
  // 取消定时任务
  async_articles.cancel();
  // 退出进程
  process.exit();
});

const router = new Router({
  prefix: "/admin/news",
});

// 同步文章
router.post("/async", async (ctx, next) => {
  await asyncArticles();
  ctx.body = {
    code: 200,
    msg: "同步成功",
  };
});


//获取新闻资讯列表
router.post("/list", new Auth(16).m, async (ctx, next) => {
  const { page, pageSize, title = "" } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const where = {
    title: {
      [Op.like]: `%${title}%`,
    },
  };

  const { count: total, rows } = await News.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]], // 排序
    paranoid: false,
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 新闻详情
router.post("/detail", async (ctx, next) => {
  const { news_id } = ctx.request.body;

  const news = await News.findOne({
    where: { news_id },
    include: [
      {
        model: Admin,
        attributes: ["admin_name", "avatar"],
        required: false,
      },
    ],
  });

  ctx.body = {
    msg: "获取成功",
    code: 200,
    data: news,
  };
});
// 新闻删除
router.post("/delete", new Auth(16).m, async (ctx, next) => {
  const { news_id } = ctx.request.body;
  if (!news_id) {
    throw new global.errs.AuthFailed("id是必传字段");
  }
  const news = await News.destroy({
    where: {
      news_id,
    },
    force: true,
  });
  await Favor.destroy({
    where: {
      news_id,
    },
    force: true,
  });

  await redis.del(`news:${news_id}`);
  ctx.body = {
    msg: "删除成功",
    code: 200,
    data: {},
  };
});
// 新闻下架/上架
router.post("/isDestroy", new Auth(16).m, async (ctx, next) => {
  const { news_id, is_destroy } = ctx.request.body;

  isNumericArray = (arr) => {
    return (
      Array.isArray(arr) &&
      arr.every((item) => {
        return typeof item === "number";
      })
    );
  };
  if (!isNumericArray(news_id)) {
    throw new global.errs.AuthFailed("id格式是数字数组");
  }

  await News.update(
    {
      is_del: is_destroy ? 1 : 0,
    },
    {
      where: { news_id: news_id },
    }
  );
  await redis.del(`news:${news_id}`);
  ctx.body = {
    msg: is_destroy ? "上架成功" : "下架成功",
    code: 200,
    data: {},
  };
});

// 发布新闻
router.post("/create", new Auth(16).m, async (ctx, next) => {
  const { content, title, image } = ctx.request.body;

  const news = await News.create({
    content,
    title,
    image,
    admin_id: ctx.auth.uid,
  });
  if (!news) {
    throw new global.errs.AuthFailed("新闻发布失败");
  }

  ctx.body = {
    msg: "创建成功",
    code: 200,
    data: {},
  };
});

// 更新新闻
router.post("/update", new Auth(16).m, async (ctx, next) => {
  const { content, title, image, news_id } = ctx.request.body;

  if (!news_id) {
    throw new global.errs.AuthFailed("id是必传字段");
  }
  const data = {
    content,
    title,
    image,
  };
  const news = await News.update(data, {
    where: {
      news_id,
    },
  });
  if (news[0] == 0) {
    throw new global.errs.AuthFailed("编辑失败");
  }
  await redis.del(`news:${news_id}`);

  ctx.body = {
    msg: "修改成功",
    code: 200,
    data: {},
  };
});

module.exports = router;
